package com.mytest.provider.service.config.security;


import com.mytest.provider.service.config.security.jwt.AuthenticationFailHandler;
import com.mytest.provider.service.config.security.jwt.AuthenticationSuccessHandler;
import com.mytest.provider.service.config.security.jwt.JwtAuthenticationFilter;
import com.mytest.provider.service.config.security.jwt.RestAccessDetailHandler;
import com.mytest.provider.service.config.security.permission.MyFilterSecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 配置SecurityConfig
 * 开启Spring Security的功能
 * @author FengJie
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 用户认证实现
     */
    @Autowired
    private UserDetailsService userDetailsService;
    /**
     * 认证成功处理
     */
    @Autowired
    private AuthenticationSuccessHandler successHandler;

    /**
     * 认证失败处理
     */
    @Autowired
    private AuthenticationFailHandler failHandler;

    /**
     * 权限拒绝处理
     */
    @Autowired
    private RestAccessDetailHandler accessDeniedHandler;

    /**
     * 自定义权限过滤
     */
    @Autowired
    private MyFilterSecurityInterceptor myFilterSecurityInterceptor;

    /**
     * 图片验证码过滤器
     */
    @Autowired
    private ValidateCodeFilter validateCodeFilter;

    /**
     * 配置BCryptPasswordEncoder 作为密码加密认证
     * @return
     */
    @Bean
    public  BCryptPasswordEncoder getBCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //根据传入的用户信息用UserDetailsService来添加身份验证
        auth.userDetailsService(userDetailsService).passwordEncoder(getBCryptPasswordEncoder());
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //将图片验证码验证其加在UsernamePasswordAuthenticationFilter之前。
        http.addFilterBefore(validateCodeFilter,UsernamePasswordAuthenticationFilter.class);

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();
        //除以下忽略路径其它所有请求都需经过认证和授权
            registry.antMatchers(
                    //数据源监控
                    "/druid/**",
                    //所有静态资源
                    "/**/*.js",
                    "/**/*.css",
                    "/**/*.png",
                    "/**/*.ico",
                    "/**/*.xls",
                    //公共相关接口
                    "/common/**/**",
                    //忽略获取菜单列表
                    "/admin/permission/sysPermission/userMenu",
                    "/admin/permission/sysPermission/allMenu",
                    //暂时忽略后台操作
                    "/admin/**",
                    "/item/**",
                    "/retailStore",
                    //对外的app接口
                    "/app/**",
                    //后台管理静态资源
                    "/manager/**",
                    //swagger-ui
                    "/swagger-resources/**",
                    "/webjars/**",
                    "/v2/**",
                    "/swagger-ui.html/**",
                    //导入导出excel
                    "/excel/export/**",
                    "/excel/import/**",
                    //评价
                    "/app/evaluate/**",
                    //myTest
                    "/user/**"
            ).permitAll();

        registry.and()
                //表单登录方式
                .formLogin()
               // .loginPage("/common/needLogin")
                //登录请求url
               // .loginProcessingUrl("/common/userLogin")

                .permitAll()
                //成功处理类
                .successHandler(successHandler)
                //失败
                .failureHandler(failHandler)
                .and()
                //允许网页iframe
                .headers().frameOptions().disable()
                .and()
                .logout()
                .permitAll()
                .and()
                .authorizeRequests()
                //任何请求
                .anyRequest()
                //需要身份认证
                .authenticated()
                .and()
                //关闭跨站请求防护
                .csrf().disable()
                //前后端分离采用JWT 不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //自定义权限拒绝处理类
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
                .and()
                //添加自定义权限过滤器,验证请求的路径有没有权限被访问
                .addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class)
                //添加JWT过滤器 除/login其它请求都需经过此过滤器,验证token是否正确
                .addFilter(new JwtAuthenticationFilter(authenticationManager()));
    }

}
